﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Text;


using log4net;

namespace StreakyDownloader.Model
{
   /// <summary>
   /// Contains a list of files to download.
   /// </summary>
   public class DownloadQueue : List<DownloadFile>
   {
      private ILog logger = LogManager.GetLogger(typeof(DownloadQueue));

      /// <summary>
      /// Create an empty list of files to download.
      /// </summary>
      public DownloadQueue()
      {
         this.Clear();
      }

      /// <summary>
      /// Populates the IDs to download from the specified file.
      /// </summary>
      /// <param name="filename">The filename containing the list of file IDs to download</param>
      /// <returns>True if the ids were read successfully, and false if they were not.</returns>
      public bool ReadIds(string filename)
      {
         bool successfulRead = false;

         try
         {
            // This text is added only once to the file. 
            if (File.Exists(filename))
            {
               string[] fileIDs = File.ReadAllLines(filename);

               // create a download file object for each ID read
               // from the file.
               foreach (string id in fileIDs)
               {
                  Add(new DownloadFile(id));
               }

               // only consider the read successful if some data was read from
               // the file and added to the download queue.
               if (0 != this.Count)
               {
                  successfulRead = true;
               }
            }
            else
            {
               logger.Warn("The file does not exist: " + filename);
            }
         }
         catch(Exception ex)
         {
            logger.Error("Unable to load the list of file IDs into the list", ex);
         }

         return successfulRead;
      }
   }
}
